﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Data.Linq;

namespace UnitTestUtils.DB
{
    /// <summary>
    /// Supports LinqToSql over SqlCe database.
    /// </summary>
    public static class DB
    {
        /// <summary>
        /// Create new db instance using a LinqToSql <see cref="DataContext"/>. Location of the db file
        /// is the Temp directory.
        /// </summary>
        /// <typeparam name="TItem"></typeparam>
        /// <returns>SqlCeConnectionWrapper is taking care of removing the db file, when it is disposed.</returns>
        public static SqlCeConnectionWrapper CreateDB<TItem>()
            where TItem : DataContext, new()
        {
            string path = System.IO.Path.GetTempPath();
            string filename;
            int i = 0;
            do
            {
                filename = System.IO.Path.Combine(path, string.Format("TestDB{0}.sdf", i++));
            } while (System.IO.File.Exists(filename));

            System.Data.SqlClient.SqlConnectionStringBuilder bld = 
                new System.Data.SqlClient.SqlConnectionStringBuilder();
            bld.DataSource = filename;

            IDbConnection con = new SqlCeConnection(bld.ConnectionString);

            TItem ctx = (TItem)Activator.CreateInstance(typeof(TItem), con);
            ctx.CreateDatabase();

            return new SqlCeConnectionWrapper(con, filename);
        }
    }
}
